

var mainCustomerId=sessionStorage.getItem("mainCustomerId")//主客户id
selectcustomers()
function selectcustomers() {
    $.ajax({
        url:root.member.getCustomers,
        cache: false,  //禁用缓存
        type: "POST",
        dataType:'json',
        contentType: "application/json",
        data: JSON.stringify({
            "pageNum":1,
            "pageSize":50,
            "customerCode":$("#customerCode").val(),
            "customerId":$("#customerId").val(),
            "customerName":$("#customerName").val(),
            "mainCustomerId":mainCustomerId,
            "isOnlyFreeOfMain":"true",
            "belongGroupId":""
        }),
        success: function (data) {
            datas=data.data.data
            couponlist(data.data, 0);
            $('.M-box3').pagination({
                pageCount: data.data.pageCount,
                jump: true,
                coping: true,
                prevContent: '上页',
                nextContent: '下页',
                callback: function (api) {
                    $("#spu_all").prop("checked",false)
                    $.ajax({
                        url: root.member.getCustomers,
                        cache: false,  //禁用缓存
                        type: "POST",
                        dataType:'json',
                        contentType: "application/json",
                        data: JSON.stringify({
                            "pageNum":api.getCurrent(),
                            "pageSize":50,
                            "customerCode":$("#customerCode").val(),
                            "customerId":$("#customerId").val(),
                            "customerName":$("#customerName").val(),
                            "mainCustomerId":mainCustomerId,
                            "isOnlyFreeOfMain":"true",
                            "belongGroupId":""

                        }),
                        success: function (result) {
                            couponlist(result.data);
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            alert(XMLHttpRequest);
                        }
                    });
                }
            });

        },
        error: function () {
            $.Huimodalalert('失败！',2000);
        }
    });
}
var dataSource = new Array();
var table;   //table对象
dataSource = [];
function couponlist(data, index){
    sessionStorage.setItem("authorizedUsers", JSON.stringify(data.data));
    dataSource.splice(0,dataSource.length);//清空数组
    if(data.data !=null && data.data != ''){
        var datashu =data.startRow+1;
        $.each(data.data, function (i, field) {
            var datashus = datashu++
            var rowData = new Array();
            rowData.push(field.customerCode);
            rowData.push(field.customerId);
            rowData.push(field.customerName);
            rowData.push(field.belongGroupName);
            rowData.push(datashus);
            rowData.push(field.enable);
            rowData.push(field.customerGrade);
            rowData.push(field.forbidden);
            rowData.push(field.isEnter);
            dataSource.push(rowData);

        });
    }
    initDataTable(dataSource);
    function initDataTable(dataSource) {

        var dttable = $('#datatable').dataTable(); // 初始化dataTable，清空上一个值
        dttable.fnClearTable(); //清空一下table
        dttable.fnDestroy(); //还原初始化了的datatable
        $("#datatable").DataTable({
            // "order": false,
            "autoWidth": false,
            "ordering": false,
            "searching": false,
            "paging": false,
            "retrieve": true,
            "destroy": true,
            "bAutoWidth": true,
            "bLengthChange": true,
            "aLengthMenu": false,
            "oLanguage": {
                "sLengthMenu": "每页显示 _MENU_ 条记录",
                "sZeroRecords": "抱歉， 没有找到",
                "sInfo": "从 _START_ 到 _END_ /共 _TOTAL_ 条数据",
                "sInfoEmpty": "没有数据",
                "sInfoFiltered": "(从 _MAX_ 条数据中检索)",
                "oPaginate": {
                    "sFirst": "首页",
                    "sPrevious": "前一页",
                    "sNext": "后一页",
                    "sLast": "尾页"
                },
                "sZeroRecords": "没有检索到数据",
            },
            data: dataSource,
            columnDefs: [
                {
                    "visible": true,
                    "targets": 0
                },
                {
                    "render": function (data, type, row, meta) {
                        if (row[5]==false||row[7]==1||row[6]=='D级'||row[8]==10){
                            var val = '<span>'+row[4]+'</span>'
                            return val;
                        }else {
                            var val = '<input type="checkbox" id="' + row[3] + '" name="regional" value="'+row[1]+'"><span>'+row[4]+'</span>'
                            return val;
                        }

                    },
                    "targets": 0
                },

                {
                    "render": function (data, type, row, meta) {
                        var val = row[0]
                        if (val == undefined) {
                            val = ''
                        }
                        return val;
                    },
                    "targets": 1
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = row[1]
                        if (val == undefined) {
                            val = ''
                        }
                        return val;
                    },
                    "targets": 2
                },
                {
                    "render": function (data, type, row, meta) {

                            if (row[5]==false||row[7]==1||row[6]=='D级'||row[8]==10){
                                val="<div class='colour'>"+row[2]+"<div>"
                            }else {
                                val=row[2]
                            }


                        return val;
                    },
                    "targets":3
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = row[3]
                        if (val == undefined) {
                            val = ''
                        }
                        return val;
                    },
                    "targets": 4
                },

                {
                    "render": function (data, type, row, meta) {
                        var val = row[6]
                        if (val == undefined) {
                            val = ''
                        }
                        return val;
                    },
                    "targets": 5
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = row[7]
                        if (val == 0) {
                            val = '启用'
                        }else if (val == 1) {
                            val = '禁用'
                        }
                        return val;
                    },
                    "targets": 6
                },
            ],
            "fnInitComplete": function(oSettings, json) {
                setBtnDis(0, $("#productManage"));
                $("#datatable").on("change", '.regional', function() {
                    var num = $(".shun").find("input[type=checkbox]:checked").length;
                    setBtnDis(num, $("#productManage"));
                });

            }
        });
    };
    $('.colour').parent().parent().css('background-color','gray');
}
function stoprop() {
    var timer = setTimeout(function() {
        var num = $("#datatable").find("tbody").find("input[type=checkbox]:checked").length;
        setBtnDis(num, $("#productManage"));
        clearTimeout(timer);
    }, 200)

    window.event ? window.event.cancelBubble = true : e.stopPropagation();
}
function setBtnDis(num, pnode) { //如果选中项为空时，置灰相关按钮
    if(num <= 0) {
        pnode.find(".goods_edit").attr("disabled", "disabled").addClass("dis_btn");
    } else {
        pnode.find(".goods_edit").removeAttr("disabled").removeClass("dis_btn");
    }
}
//取消
function cancel() {
    var indexs = parent.location.reload();
    parent.layer.close(indexs);
}

//确认
function customerssave() {
    $('input:checkbox[name="regional"]:checked').val()
    var curObj={}
    var regional=document.getElementsByName("regional");
    var objArrdd = [];
    var customerIds=""
    for(var  i=0;i<regional.length;i++){
        if(regional[i].checked==true) {

            var vals=regional[i].value
            objArrdd.push(vals)
            customerIds= objArrdd.join(",")
        }
    }
    console.log(customerIds)
    if(customerIds==""){
        $.Huimodalalert("请选择数据",2000);
        return false;
    }
    var user_data = {
        "customerIds":customerIds,
    }
    var succCallBack = function (data, status, response) {
        if(data.code=="20"){
            var cu = layer.confirm("是否确认添加此客户<br>添加后，该客户下的会员会自动加入账号池，并生成三全合一的权限,客户代码"+data.data, {title:'提示',btn: ['确认', '取消']}, function(index){
                    $.ajax({
                        url:root.member.relationMainCustomer,
                        cache: false,  //禁用缓存
                        type: "POST",
                        dataType:'json',
                        contentType: "application/json",
                        data: JSON.stringify({
                            "manCustomerId":mainCustomerId,
                            "customerIds":customerIds,
                            "removeRelation":"false",
                        }),
                        success: function (data) {
                            if(data.errorCode==0){
                                layer.msg("保存成功",{icon: 6,time:2000},function () {
                                    /*var index = parent.layer.getFrameIndex(window.name);
                                    parent.layer.close(index);*/ //跳转父页面
                                    setTimeout(function () {
                                        window.parent.conter();
                                        var index = parent.layer.getFrameIndex(window.name);
                                        parent.layer.close(index);
                                    })
                                });
                            }else if (data.errorCode==1) {
                                console.log(data.msg)
                                $("#customerTips").modal("show");
                                $("#customerTipss").html(data.msg)
                            }else {
                                $.Huimodalalert(data.msg,2000);
                            }
                        },
                        error: function () {
                            $.Huimodalalert('失败！',2000);
                        }
                    });
                    layer.close(cu);
                },function(){
                    layer.close(cu);

                });
        }else if(data.code=="0"){
            $.ajax({
                url:root.member.relationMainCustomer,
                cache: false,  //禁用缓存
                type: "POST",
                dataType:'json',
                contentType: "application/json",
                data: JSON.stringify({
                    "manCustomerId":mainCustomerId,
                    "customerIds":customerIds,
                    "removeRelation":"false",
                }),
                success: function (data) {
                    if(data.errorCode==0){
                        layer.msg("保存成功",{icon: 6,time:2000},function () {
                            /*var index = parent.layer.getFrameIndex(window.name);
                            parent.layer.close(index);*/ //跳转父页面
                            setTimeout(function () {
                                window.parent.conter();
                                var index = parent.layer.getFrameIndex(window.name);
                                parent.layer.close(index);
                            })
                        });
                    }else if (data.errorCode==1) {
                        console.log(data.msg)
                        $("#customerTips").modal("show");
                        $("#customerTipss").html(data.msg)
                    }else {
                        $.Huimodalalert(data.msg,2000);
                    }
                },
                error: function () {
                    $.Huimodalalert('失败！',2000);
                }
            });
        }else{
            $.Huimodalalert(data.msg,2000);
        }
    }
    web.doAjax(root.member.queryUpgradeCustomer,'post',user_data, succCallBack,1);



    
}